package strategies;

import exceptions.DatabaseException;
import general.IContext;
import java.util.*;
import java.util.logging.*;

/**
 *
 * @author Alejandro
 */
public abstract class EditPageStrategy extends AbstractStrategy {

    protected boolean isEditAllowed;
    protected Integer day = 0, month = 0, year = 0, editId;
    protected Object e;

    protected abstract void commitRow(Object e) throws DatabaseException;

    protected abstract Object writeInfo();

    protected String leadingZero(int i) {
        if (i < 10) {
            return "0" + i;
        } else {
            return Integer.toString(i);
        }
    }

    @Override
    public void executeOperation(IContext context) {
        prepareContext(context);
        editId = 0;
        if (pp.hasParam("new") || pp.hasParam("edit")) {
            isEditAllowed = false;
            e = null;
            op.echo("<div id=\"control\">");
            op.echo("<p>Enter data in fields below</p>");
            op.putSubmit("Back", "back");
            op.echo("<a href=\"help.html\">Help</a>");
            if (pp.hasParam("new")) {
                op.putSubmit("Add row", "new_add");
            } else if (pp.hasParam("edit")) {
                Set<String> keys = pp.getParamMap().keySet();
                for (String s : keys) {
                    if (s.startsWith("row_")) {
                        int newId = Integer.parseInt(s.replace("row_", ""));
                        if (pp.getParam(s).compareTo("on") == 0) {
                            editId = newId;
                            break;
                        }
                    }
                }
                if (editId == 0) {
                    op.putErrorReport("No rows were selected. Only adding new row is allowed", "");
                } else {
                    
                    try {
                        e = dao.selectById(editId);
                        e=writeInfo();
                        isEditAllowed = true;
                        op.echo("<input type=\"hidden\" name=\"edit_id\" id=\"edit_id\" value=\"" + editId + "\" />");
                    } catch (DatabaseException de) {
                        op.putErrorReport("Selecting from database failed. Only adding new row is allowed", de.getMessage());
                    }
                }
                if (isEditAllowed) {
                    op.putSubmit("Edit row", "new_edit");
                } else {
                    op.putSubmit("Add row", "new_add");
                }
            }

            op.echo("</div>");
            op.echo("<input type=\"hidden\" name=\"table-selection\" id=\"table-selection\" value=\"" + pp.getParam("table-selection") + "\" />");

            try {
                commitRow(e);
            } catch (DatabaseException ex) {
                Logger.getLogger(EditPageStrategy.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
